package com.xiaoqiudong.forum.interceptor;

import com.xiaoqiudong.forum.config.AppConfig;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * Created with IntelliJ IDEA
 * Descroption
 * User:dell
 * Date:2025-08-25
 * Time:10:09
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${bit-forum.login.url}")
    private String defaultUrl;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(AppConfig.USER_SESSION) != null){
            return true;
        }
        if (!defaultUrl.startsWith("/")){
            defaultUrl = "/"+defaultUrl;
        }
        //校验不通过，返回登录界面
        response.sendRedirect(defaultUrl);
        return false;
    }
}
